<?php

namespace Library\Auth;

class User {

	private $_user;
	private $_auths;
	
	public function __construct( \Bean\Db\User $user ) {
		$this->_user = $user;
	}
	
	public function getUser() {
		return $this->_user;
	}

	public function connect() {

		$this->_updateConnectionTime();
		$this->_deleteOldSessions();
		return $this;
	}
	
	public function getAuths() {
		
		$auths = array();
		$basics = _q()->getN( 'auth_basics', array( 'user_id' => $this->getUser()->getUserId() ) );
		foreach( $basics as $basic ) {
			$auths[] = new BasicAuth( $basic );
		}
		return $auths;
	}

	private function _updateConnectionTime() {
		$query = _q()->upt( 'users', 
			array( 'connection_time' => _now() ),
			array( 'user_id' => $this->getUser()->getUserId() )
		);
		return $this;
	}
	
	private function _deleteOldSessions() {
	
		$sessionConf = \Library\Config::get( 'session' );
		$sessions = _q()->getN( 'users_sessions', array( 'user_id' => $this->getUser()->getUserId() ) );
		foreach( $sessions as $session ) {
			if( strtotime($session['creation_time']) + $sessionConf['remembrance']['ttl'] < time() ) {
				_q()->del( 'users_sessions', array( 'session_id' => $session['session_id'] ) );
			}
		}
		return $this;
	}
}
